<?php
//module game đã chơi của user
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class user_game_play_module extends CI_Module {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
    public $mytable = "user_game_play";
    public $primaryKey = "ugame_play_id";
    public $resCode = "USER_GAME_PLAY";

	public function init() {
		$this->load->model('muser');
	}
	
	public function active() {
		
	}
	
	public function deactive() {
		
	}
	
	public function admin($config) {
		$this->view('admin', $config);
	}
	
	public function run($config) {
		$game_id = @$this->msystem->get_global('game_id');
		if(isset($game_id ) && $game_id >0){
			$this->update_game($game_id);
		}
		if (!isset($config['view'])) {
			$config['view'] = 'index';
		}
		if (!isset($config['num'])) {
			$config['num'] = 30;
		}
		$config['use_id'] = ((isset($config['use_id']) && $config['use_id'] >0)?$config['use_id']:$this->muser->use_id);
		switch ($config['view']) {
			case 'index' :
				$config['games'] = $this->get_game_by_user(@$config['use_id'], $config['num']);
				// prd($config['games']);
			break;
			
			case 'add' :
			break;
		}
		if($config['view'] !='null')
			$this->view($config['view'], $config);
	}
	
    function field() {
		$fieldData = array();
		$fieldData['use_id'] = 0;
		$fieldData['game_id'] = 0;
		$fieldData['ugame_play_num'] = 0;
		$fieldData['ugame_play_time_update'] = time();
		return $fieldData;
    }
	
	function update_game($game_id = 0, $user_id = 0)
	{
		if($user_id  == 0){
			$user_id  = $this->muser->use_id;
		}
		if(!$user_id || $user_id<=0)
			return '';
		$check = $this->get(array('use_id'=>$user_id, 'game_id'=>$game_id ));
		if($check){
			$this->db->set('ugame_play_num', 'ugame_play_num+1', false);
			$this->db->set('ugame_play_time_update',time(), false);
			$this->db->where(array('use_id'=>$user_id, 'game_id'=>$game_id ));
			$this->db->update($this->mytable, array());
		}
		else {
			$this->insert(array('use_id'=>$user_id, 'game_id'=>$game_id,'ugame_play_num' =>1));
		}
	}

	//Model 
	function get_game_by_user($user_id = 0, $limit = 30) {
		if ($user_id > 0)
		return $this->db
				->from($this->mytable . ' as gp')
				->join('game as g', 'g.game_id = gp.game_id')
				->limit($limit)
				->where ('gp.use_id = ', $user_id)
				//->order_by('ugame_play_id desc')
				->get()->result();
		return null;
	}
}

?>